package helper

import (
	"backend/define"
	"errors"
	"github.com/dgrijalva/jwt-go"
)

// 生成token函数
func GenerateToken(id uint, name string, role_id uint, exprieAt int64) (string, error) {
	uc := define.UserClaims{
		Id:     id,
		Name:   name,
		RoleId: role_id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: exprieAt,
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, uc)
	tokenString, err := token.SignedString([]byte(define.JwtKey))
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// AnalyzeToken 解析token
func ParseToken(tokenString string) (*define.UserClaims, error) {
	uc := new(define.UserClaims)
	claims, err := jwt.ParseWithClaims(tokenString, uc, func(token *jwt.Token) (interface{}, error) {
		return []byte(define.JwtKey), nil
	})
	if err != nil {
		return nil, err
	}

	if !claims.Valid {
		return uc, errors.New("invalid token")
	}
	return uc, nil
}
